package com.jsjosem.aftersales.ui;

import static com.google.android.material.navigation.NavigationBarView.LABEL_VISIBILITY_LABELED;
import static com.igexin.base.api.GTBase.context;
import static com.jsjosem.aftersales.constant.Command.NOTIFICATION_UNREAD_COUNT_UPDATE;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.igexin.sdk.GetuiPushException;
import com.igexin.sdk.PushManager;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.api.NotificationsApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.component.ConfirmDialog;
import com.jsjosem.aftersales.component.DotView;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.NotificationCountResponse;
import com.jsjosem.aftersales.databinding.ActivityMainBinding;
import com.jsjosem.aftersales.listener.IListener;
import com.jsjosem.aftersales.listener.ListenerManager;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.utils.CompatResourceUtils;

import retrofit2.Call;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity implements IListener {

    public ActivityMainBinding binding;

    private static final String TAG = MainActivity.class.getName();

    private BottomNavigationView bottomNavigationView;
    private DotView dotView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initGeTuiPush();
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        ConstraintLayout view = binding.getRoot();
        setContentView(view);
        // 检测用户是否打开通知
        boolean notificationsEnabled = PushManager.getInstance().areNotificationsEnabled(this);
        if (!notificationsEnabled) {
            // 没有打开，就引导用户打开通知权限
            ConfirmDialog confirmDialog = new ConfirmDialog(this, () -> {
                // 确认打开通知
                PushManager.getInstance().openNotification(this);
            });
            confirmDialog.setTitle("提示");
            confirmDialog.setContent("请确认打开通知权限，方便接收工作消息。");
        }
        ListenerManager.getInstance().registerListener(this);
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        NavController navController = navHostFragment.getNavController();
        bottomNavigationView = findViewById(R.id.nav_view);
        bottomNavigationView.setLabelVisibilityMode(LABEL_VISIBILITY_LABELED);
        initNotifyMenuUnReadMessageViews();
        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

    private void initGeTuiPush() {
        PushManager instance = PushManager.getInstance();
        try {
            instance.checkManifest(this);
        } catch (Exception | GetuiPushException e) {
            e.printStackTrace();
        }
        instance.initialize(getApplicationContext());
        boolean notificationsEnabled = PushManager.getInstance().areNotificationsEnabled(context);
        if (!notificationsEnabled) {
            PushManager.getInstance().openNotification(context);
        }

    }

    private void initNotifyMenuUnReadMessageViews() {
        //初始化红点view
        BottomNavigationMenuView menuView = null;
        for (int i = 0; i < bottomNavigationView.getChildCount(); i++) {
            View child = bottomNavigationView.getChildAt(i);
            if (child instanceof BottomNavigationMenuView) {
                menuView = (BottomNavigationMenuView) child;
                break;
            }
        }
        if (menuView != null) {
            int dp8 = CompatResourceUtils.getDimensionPixelSize(this, R.dimen.space_8dp);
            BottomNavigationItemView.LayoutParams params = new BottomNavigationItemView.LayoutParams(2 == menuView.getChildCount() - 1 ? dp8 : dp8 * 2, 0);
            params.gravity = Gravity.CENTER_HORIZONTAL;
            params.leftMargin = dp8 * 3;
            params.topMargin = dp8 / 2;
            BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(2);
            dotView = new DotView(this);
            dotView.setBackgroundColor(Color.RED);
            dotView.setTextColor(Color.WHITE);
            dotView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
            dotView.setVisibility(View.GONE);
            itemView.addView(dotView, params);
            loadUnreadCount();
        }
    }

    @Override
    public void notifyAllActivity(int flag, String data, String message) {
        if (flag == NOTIFICATION_UNREAD_COUNT_UPDATE) {
            loadUnreadCount();
        }
    }

    private void loadUnreadCount() {
        Retrofit retrofit = RetrofitClient.getInstance();
        NotificationsApi notificationsApi = retrofit.create(NotificationsApi.class);
        Call<BaseResponse<NotificationCountResponse>> statusCountCall = notificationsApi.statusCount();
        AsyncRequest<BaseResponse<NotificationCountResponse>> request = new AsyncRequest<>();
        request.sendRequest(statusCountCall, res -> {
            dotView.setVisibility(View.VISIBLE);
            dotView.setUnReadCount(res.getData().getUnread());
        }, errMsg -> {
        });
    }
}